import React from 'react'
import { Upload, message } from 'antd'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons'
import { session } from 'utils'
import { SERVER } from 'configs/service'

export default function UploadImg(props) {
  const { title, required = false, action, uploadimg, url } = props
  const [loading, setLoading] = React.useState()

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8, color: '#666' }}>Upload</div>
    </div>
  )

  function beforeUpload(file) {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'pdf'
    if (!isJpgOrPng) {
      message.error('只能上传jepg，png，pdf')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return isJpgOrPng && isLt2M
  }

  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, () => {
        setLoading(false)
        if (info.file.response && info.file.response.code === 1) {
          uploadimg(info.file.response.data)
        } else {
          message.error('上传图片失败')
          uploadimg(null)
        }
      })
    }
  }

  function getBase64(img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  return (
    <div style={{ width: 120, margin: '0 auto' }}>
      <Upload
        listType="picture-card"
        headers={{ Authorization: session.Authorization }}
        className="avatar-uploader"
        accept="image/png,image/jpg,image/jpeg,.pdf"
        showUploadList={false}
        action={action}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {url ? (
          <img
            src={`${SERVER}/uploadFile/base64Read?id=${url}&Authorization=${session.Authorization}`}
            alt="avatar"
            style={{ width: '100%' }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
      {title ? (
        <div
          style={{
            width: '100%',
            textAlign: 'center',
            overflow: 'hidden',
            whiteSpace: 'nowrap',
          }}
        >
          {required ? <span style={{ color: 'red' }}> * </span> : null}
          {title}
        </div>
      ) : null}
    </div>
  )
}
